<?php

Raise::load('core.io.RaiseStream');

/**
 * RaiseBufferStream class
 * Streaming information to a string buffer
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package phpraise.core.io
 * @since 1.2
 */
class RaiseBufferStream extends RaiseStream {

    private $buffer = '';

    function __construct($buffer) {
        $this->buffer = $buffer;
    }

    public function close() {
    }

    public function length() {
        return strlen($this->buffer);
    }

    public function isReadable() {
        return true;
    }

    public function isSeekable() {
        return true;
    }

    public function isWriteable() {
        return true;
    }

    public function read($l) {
        $ret = substr($this->buffer, $this->position(), $l);
        $this->position($this->position() + $l);
        return $ret;
    }

    public function readByte() {
        return ord($this->read(1));
    }

    public function seek($position) {
        $this->position($position);
    }

    public function write($str) {
        if($this->position() + strlen($str) > $this->length()){
            $this->buffer = substr($this->buffer, 0, $this->position())  .$str;
        }else{
            $this->buffer = substr($this->buffer, 0, $this->position()) . $str . substr($this->buffer, $this->position() + strlen($str));
        }
        $this->position($this->position() + strlen($str));
    }

    public function writeByte($i) {
        $this->write(chr($i));
    }
    
}
